package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.compete;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.compete.CompeteTenderBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysFiles;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CompeteTenderExcelEn;
import com.xiaoxu.intranetweb.util.PermissionCheck;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
@RequestMapping(value = "/CompeteTender")
public class CompeteTenderController {
    @Autowired
    private CompeteTenderBu CompeteTenderBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private WebFunctionUtil webFunctionUtil;

    //新增投标信息控制层
    @PostMapping("/addCompeteTender")
    @PermissionCheck("competeTender_addCompeteTender")
    public SzResult addCompeteTender(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String competeId = jsonObject.getString("competeId");
        String PdtId = jsonObject.getString("PdtId");
        String price = jsonObject.getString("price");
        String weight = jsonObject.getString("weight");
        String winBidPrice = jsonObject.getString("winBidPrice");
        String winBidWeight = jsonObject.getString("winBidWeight");
        String co = jsonObject.getString("co");
        String chiCo = jsonObject.getString("chiCo");
        String status = jsonObject.getString("status");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return CompeteTenderBu.addCompeteTender(competeId, PdtId, price, weight, winBidPrice, winBidWeight,co,chiCo,status, token,plantId);

    }

    //删除投标信息控制层
    @GetMapping("/deleteCompeteTender")
    @PermissionCheck("competeTender_deleteCompeteTender")
    public SzResult deleteCompeteTender(@RequestParam String id, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return CompeteTenderBu.deleteCompeteTender(id,token,plantId);
    }

    //修改投标信息控制层
    @PostMapping("/updateCompeteTender")
    @PermissionCheck("competeTender_updateCompeteTender")
    public SzResult updateCompeteTender(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        String pdtId = jsonObject.getString("pdtId");
        String price = jsonObject.getString("price");
        String weight = jsonObject.getString("weight");
        String winBidPrice = jsonObject.getString("winBidPrice");
        String winBidWeight = jsonObject.getString("winBidWeight");
        String winBid = jsonObject.getString("winBid");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return CompeteTenderBu.updateCompeteTender(id, pdtId, price, weight, winBidPrice, winBidWeight, winBid,token,plantId);
    }

    //查询投标信息控制层
    @PostMapping("/getCompeteTender")
    public SzResult getCompeteTender(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String page = jsonObject.getString("page");
        String pageSize = jsonObject.getString("pageSize");
        String competeId = jsonObject.getString("competeId");
        String pdtId = jsonObject.getString("pdtId");
        String cpyId = jsonObject.getString("cpyId");
        String winBid = jsonObject.getString("winBid");
        String sortStatus = jsonObject.getString("sortStatus");
        String winBidStauts = jsonObject.getString("winBidStauts");
        String plantId = request.getHeader("Plant-Id");
        return CompeteTenderBu.getCompeteResult(page, pageSize,competeId, pdtId, cpyId, winBid,sortStatus,winBidStauts,plantId);
    }

    /**
     * 竞标结果详情
     */
    @GetMapping("/competeResultDetail")
    public SzResult competeResultDetail(@RequestParam String id,HttpServletRequest request) throws Exception {
        String plantId = request.getHeader("Plant-Id");
        return CompeteTenderBu.competeResultDetail(id,plantId);
    }

    //    上传文件接口
    @PostMapping("/upload")
    @PermissionCheck("file_upload")
    public SzResult upload(@RequestParam("file") MultipartFile file,
                           @RequestParam(required = false) String connId, HttpServletRequest request,
                           HttpServletResponse response) throws Exception {
        String token = request.getHeader("Authorization");
        return CompeteTenderBu.uploadFile(file, connId, token);
    }

    //    下载文件接口
    @GetMapping("/download")
    public void downloadFile(@RequestParam("fileId") String fileId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        try {
            SysFiles sysFiles = CompeteTenderBu.downloadFile(fileId);
            Path path = Paths.get(sysFiles.getFilePath() + sysFiles.getId() + "." + sysFiles.getFileType());
            String fileName = sysFiles.getFileName();
            InputStream inputStream = new BufferedInputStream(Files.newInputStream(new File(path.toString()).toPath()));
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setHeader("Content-Length", "" + path.toFile().length());
            response.setHeader("Content-Disposition", "attachment; filename*=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] bytes = new byte[1024];
            int len = 0 ;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            response.setStatus(500);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            e.printStackTrace();
        }
    }

    //    删除文件接口
    @GetMapping("/deleteFile")
    @PermissionCheck("file_deleteFile")
    public SzResult deleteFile(@RequestParam("fileId") String fileId,HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            return CompeteTenderBu.deleteFile(fileId);
        } catch (Exception e) {
            e.printStackTrace();
            return SzResult.error(e.getMessage());
        }
    }

    //    预览文件接口
    @GetMapping("/previewFile")
    @PermissionCheck("file_previewFile")
    public SzResult previewFile(@RequestParam("fileId") String fileId, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            Path path = CompeteTenderBu.previewFile(fileId);
            if (path == null) {
//               无文件
                return SzResult.error("无文件或该文件类型暂不支持预览");
            }
//            根据path拿到文件数据
            InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(path.toString())));
//            转base64
            OutputStream outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            String base64 = Base64.getEncoder().encodeToString(((ByteArrayOutputStream) outputStream).toByteArray());
//            关闭流
            outputStream.flush();
            outputStream.close();
            inputStream.close();
//            返回数据
            return SzResult.success(base64);
        } catch (Exception e) {
            e.printStackTrace();
            return SzResult.error(e.getMessage());
        }
    }

    /**
     * 导出excel
     * @param jsonParam 传入的参数 filename 文件名  fields 实体类  ids 数据  isHeader 是否有表头
     * @param response 响应
     * @param request 请求
     * @throws IOException IO异常
     * @throws ExecutionException 异常
     * @throws InterruptedException 异常
     * @return void 无返回值 IO流
     */
    @PostMapping("/exportExcel")
    public void exportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        List<Map<String,Object>> fields = jsonParam.getObject("fields", List.class);
        String filename = jsonParam.getString("filename");
        List<Map<String,Object>> ids = jsonParam.getObject("ids", List.class);
        boolean isHeader = jsonParam.getBoolean("isHeader");
        String mode = jsonParam.getString("mode");
        Boolean original = jsonParam.getBoolean("original");
        Map<String,String> pager = jsonParam.getObject("pager", Map.class);
        Map<String,String> form = jsonParam.getObject("form", Map.class);
        String sheetName = jsonParam.getString("sheetName");
        Future<List<CompeteTenderExcelEn>> listFuture = CompeteTenderBu.exportExcel(fields,ids,filename,isHeader,mode,original,pager,form,sheetName,response,token);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<CompeteTenderExcelEn> list = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CompeteTenderExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("品种")
                .doWrite(list);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}
